package com.mall.admin.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mall.admin.interceptor.AdminHolder;
import com.mall.commons.utils.JwtUtils;
import com.mall.commons.utils.R;
import com.mall.domain.*;
import com.mall.interface1.api.*;
import com.mall.vo.UmsAdminPageVo;
import com.mall.vo.UmsAdminVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UmsAdminService {
    @DubboReference
    private UmsAdminApi umsAdminApi;
    @DubboReference
    private UmsMenuApi umsMenuApi;
    @DubboReference
    private UmsRoleApi umsRoleApi;
    @DubboReference
    private UmsAdminRoleRelationApi umsAdminRoleRelationApi;
    @DubboReference
    private UmsRoleMenuRelationApi umsRoleMenuRelationApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    public R login(Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");
        UmsAdmin umsAdmin = umsAdminApi.findByUms(username, password);
        if(ObjectUtil.isNull(umsAdmin)){
            return R.error(201,"用户名或密码错误");
        }
        Map<String, Object> map1 = new HashMap<>();
        map1.put("username",username);
        map1.put("id",umsAdmin.getId());
        String token = JwtUtils.getToken(map1);
        stringRedisTemplate.opsForValue().set("token", JSON.toJSONString(map1), Duration.ofDays(30));
        HashMap<String, String> result = new HashMap<>();
        result.put("tokenHead","Bearer ");
        result.put("token",token);
        return R.success("操作成功",result);
    }

    public R getUserInfo() {
        Long userId = AdminHolder.getUserId();
        UmsAdmin umsAdmin=umsAdminApi.query(userId);
        UmsAdminVo vo = new UmsAdminVo();
        if(!ObjectUtil.isNull(umsAdmin)){
            vo.setUsername(umsAdmin.getUsername());
            vo.setIcon(umsAdmin.getIcon());
        }
        //根据用户id查权限id
        List<Long> roleIds = null;
        List<UmsAdminRoleRelation> umsAdminRoleRelation =umsAdminRoleRelationApi.query(userId);
        if(CollUtil.isNotEmpty(umsAdminRoleRelation)) {
           roleIds = CollUtil.getFieldValues(umsAdminRoleRelation, "roleId", Long.class);
        }
        //根据权限id查name
        List<UmsRole> umsRole =umsRoleApi.queryId(roleIds);
        Map<Long, Object> map = new HashMap<>();

        List<String>list=new ArrayList<>();

        if(CollUtil.isNotEmpty(umsRole)){
            for (UmsRole role : umsRole) {
                map.put(role.getId(),role.getName());
                list.add(role.getName());
            }
        }
        List<Long> ids = CollUtil.getFieldValues(umsRole, "id", Long.class);
        //根据权限ids查meun_id
         List<UmsRoleMenuRelation> umsRoleMenuRelation=umsRoleMenuRelationApi.query(ids);
         List<Long> menuIds = CollUtil.getFieldValues(umsRoleMenuRelation, "menuId", Long.class);
         List<UmsMenu> menus=umsMenuApi.queryId(menuIds);
         //// TODO: 2022/12/16 数组
         vo.setRoles(list);
         vo.setMenus(menus);
         return R.success("操作成功",vo);
    }

    public R deleteUser(Integer id) {
        umsAdminApi.deleteUser(id);
        return R.success("删除成功",new ArrayList<>());
    }

    public R listAll(Integer pageNum, Integer pageSize, String keyword) {
        UmsAdminPageVo<UmsAdmin> vo = new UmsAdminPageVo<>();
        IPage<UmsAdmin> iPage=umsAdminApi.listAll(pageNum, pageSize, keyword);
        vo.setList(iPage.getRecords());
        vo.setPageNum(pageNum);
        vo.setPageSize(pageSize);
        vo.setTotal((int) iPage.getTotal());
        vo.setTotalPage((int) iPage.getPages());
       return R.success("",vo);
    }

    public R logout(String token) {
        token = token.replaceAll("Bearer ","");
        stringRedisTemplate.delete("token");
        return R.success("",null);
    }

    //刷新token
    public R refreshToken(String token) {
        token = token.replaceAll("Bearer ","");
        String umsAdminJson = stringRedisTemplate.opsForValue().get("token");
        stringRedisTemplate.opsForValue().set("token",umsAdminJson, Duration.ofDays(30));
        //准备返回数据
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("token",token);
        resultMap.put("tokenHead","Bearer ");
        return R.success("",resultMap);
    }

    public R register(UmsAdmin umsAdmin) {
        umsAdminApi.save(umsAdmin);
        return R.success("",null);
    }

    public R updateRole(Map<String,Object> map) {
        Long adminId = (Long) map.get("adminId");
        List<Long> roleIds = (List<Long>) map.get("roleIds");
        for (Long roleId : roleIds) {
            UmsAdminRoleRelation re = new UmsAdminRoleRelation();
            re.setAdminId(adminId);
            re.setRoleId(roleId);
            umsAdminRoleRelationApi.save(re);
        }
        return R.success("",roleIds.size());
    }

    public R getRole(Long adminId) {
        List<UmsAdminRoleRelation> list = umsAdminRoleRelationApi.query(adminId);
        List<Long> roleIds = CollUtil.getFieldValues(list, "roleId", Long.class);
        List<UmsRole> umsRoles = umsRoleApi.queryId(roleIds);
        return R.success("",umsRoles);
    }
    public R updateAdmin(UmsAdmin umsAdmin) {
        umsAdminApi.update(umsAdmin);
        return R.success("",null);
    }

    public R updatepassword(Map<String, String> map) {
        String newPassword = map.get("newPassword");
        String oldPassword = map.get("oldPassword");
        String username = map.get("username");
        UmsAdmin umsAdmin=umsAdminApi.queryUser(oldPassword,username);
        if(!ObjectUtil.isNull(umsAdmin)){
            umsAdmin.setPassword(newPassword);
            umsAdminApi.update(umsAdmin);
        }
        return R.success("",null);
    }

    public R updatestatus(Integer status, Integer id) {
        UmsAdmin umsAdmin = umsAdminApi.query(Convert.toLong(id));
        umsAdmin.setStatus(status);
        umsAdminApi.update(umsAdmin);
        return R.success("",null);
    }

    public R get(Integer id) {
        UmsAdmin query = umsAdminApi.query(Convert.toLong(id));
        return R.success("",query);
    }
}
